﻿using System;
using System.ComponentModel.DataAnnotations;

namespace VisionCloud.Domain.ModelAttribute
{
    /// <summary>
    /// asc desc排序特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
        AllowMultiple = false)]
    public class AscDescAttribute : ValidationAttribute
    {
        internal static string errorMessageString = "The {0} field must be ASC or DESC";

        /// <summary>
        /// 构造函数
        /// </summary>
        public AscDescAttribute():base(()=> errorMessageString)
        {
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            this.ErrorMessage = errorMessageString;
            return string.Format(errorMessageString, name);
        }

        /// <summary>
        /// 检验
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            if (string.IsNullOrEmpty(value?.ToString()))
                return true;

            var str = value.ToString().Trim();
            return str.ToUpper() == "ASC" || str.ToUpper() == "DESC";
        }
    }
}
